<template>
  <div class="process-route-management">
    <!-- 页面标题和操作 -->
    <div class="page-header">
      <div class="header-left">
        <h1>工艺路线管理</h1>
        <p>产品制造工艺流程定义和管理</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showCreateDialog">
          <el-icon><Plus /></el-icon>
          新建工艺路线
        </el-button>
        <el-button @click="importRoutes">
          <el-icon><Upload /></el-icon>
          导入
        </el-button>
        <el-button @click="exportRoutes">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </div>
    </div>

    <!-- 统计概览 -->
    <div class="stats-overview">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon total">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ routeStats.totalRoutes }}</div>
                <div class="stats-label">工艺路线总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon active">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ routeStats.activeRoutes }}</div>
                <div class="stats-label">启用路线</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon steps">
                <el-icon><Connection /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ routeStats.totalSteps }}</div>
                <div class="stats-label">工艺步骤总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon efficiency">
                <el-icon><TrendCharts /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ routeStats.avgEfficiency }}%</div>
                <div class="stats-label">平均效率</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选和搜索 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" inline>
        <el-form-item label="产品名称">
          <el-input
            v-model="filterForm.productName"
            placeholder="请输入产品名称"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="工艺类型">
          <el-select v-model="filterForm.processType" placeholder="全部" clearable @change="handleSearch">
            <el-option label="装配工艺" value="assembly" />
            <el-option label="加工工艺" value="machining" />
            <el-option label="包装工艺" value="packaging" />
            <el-option label="测试工艺" value="testing" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="全部" clearable @change="handleSearch">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
            <el-option label="草稿" value="draft" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 工艺路线列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>工艺路线列表</span>
          <div class="header-actions">
            <el-button-group>
              <el-button :type="viewMode === 'table' ? 'primary' : ''" @click="setViewMode('table')">
                <el-icon><Grid /></el-icon>
                表格视图
              </el-button>
              <el-button :type="viewMode === 'flow' ? 'primary' : ''" @click="setViewMode('flow')">
                <el-icon><Share /></el-icon>
                流程视图
              </el-button>
            </el-button-group>
          </div>
        </div>
      </template>

      <!-- 表格视图 -->
      <div v-show="viewMode === 'table'">
        <el-table
          :data="filteredRoutes"
          style="width: 100%"
          row-key="id"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="routeCode" label="路线编码" width="120" />
          <el-table-column prop="routeName" label="路线名称" min-width="200">
            <template #default="{ row }">
              <div class="route-name">
                <span class="name">{{ row.routeName }}</span>
                <el-tag v-if="row.isDefault" type="success" size="small">默认</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="productName" label="关联产品" width="150" />
          <el-table-column prop="processType" label="工艺类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getProcessTypeColor(row.processType)">{{ getProcessTypeText(row.processType) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="stepCount" label="工艺步骤" width="100" align="center" />
          <el-table-column prop="totalTime" label="总工时(小时)" width="120" align="center" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="version" label="版本" width="80" align="center" />
          <el-table-column prop="updateTime" label="更新时间" width="180" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="viewRoute(row)">
                查看
              </el-button>
              <el-button size="small" @click="editRoute(row)">
                编辑
              </el-button>
              <el-dropdown @command="handleCommand">
                <el-button size="small">
                  更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="{action: 'copy', row}">复制</el-dropdown-item>
                    <el-dropdown-item :command="{action: 'version', row}">版本管理</el-dropdown-item>
                    <el-dropdown-item :command="{action: 'activate', row}" v-if="row.status !== 'active'">启用</el-dropdown-item>
                    <el-dropdown-item :command="{action: 'deactivate', row}" v-if="row.status === 'active'">禁用</el-dropdown-item>
                    <el-dropdown-item :command="{action: 'delete', row}" divided>删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 流程视图 -->
      <div v-show="viewMode === 'flow'" class="flow-view">
        <div class="flow-container">
          <div
            v-for="route in filteredRoutes"
            :key="route.id"
            class="flow-route"
            @click="selectRoute(route)"
            :class="{ 'route-selected': selectedRoute?.id === route.id }"
          >
            <div class="route-header">
              <h3>{{ route.routeName }}</h3>
              <el-tag :type="getStatusType(route.status)">{{ getStatusText(route.status) }}</el-tag>
            </div>
            
            <div class="route-flow">
              <div
                v-for="(step, index) in route.steps"
                :key="step.id"
                class="flow-step"
              >
                <div class="step-node">
                  <div class="step-number">{{ index + 1 }}</div>
                  <div class="step-content">
                    <div class="step-name">{{ step.stepName }}</div>
                    <div class="step-info">
                      <span>{{ step.workCenter }}</span>
                      <span>{{ step.standardTime }}h</span>
                    </div>
                  </div>
                </div>
                
                <div v-if="index < route.steps.length - 1" class="step-arrow">
                  <el-icon><ArrowRight /></el-icon>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 创建/编辑工艺路线对话框 -->
    <el-dialog
      v-model="routeDialogVisible"
      :title="isEdit ? '编辑工艺路线' : '新建工艺路线'"
      width="1000px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="routeFormRef"
        :model="routeForm"
        :rules="routeRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="路线编码" prop="routeCode">
              <el-input v-model="routeForm.routeCode" placeholder="请输入路线编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="路线名称" prop="routeName">
              <el-input v-model="routeForm.routeName" placeholder="请输入路线名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="关联产品" prop="productId">
              <el-select v-model="routeForm.productId" placeholder="请选择产品" style="width: 100%">
                <el-option
                  v-for="product in products"
                  :key="product.id"
                  :label="product.name"
                  :value="product.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工艺类型" prop="processType">
              <el-select v-model="routeForm.processType" placeholder="请选择工艺类型" style="width: 100%">
                <el-option label="装配工艺" value="assembly" />
                <el-option label="加工工艺" value="machining" />
                <el-option label="包装工艺" value="packaging" />
                <el-option label="测试工艺" value="testing" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="版本号" prop="version">
              <el-input v-model="routeForm.version" placeholder="请输入版本号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="routeForm.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="草稿" value="draft" />
                <el-option label="启用" value="active" />
                <el-option label="禁用" value="inactive" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="描述">
          <el-input
            v-model="routeForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入工艺路线描述"
          />
        </el-form-item>
        
        <el-form-item>
          <div class="form-section-header">
            <span>工艺步骤</span>
            <el-button type="primary" size="small" @click="addStep">
              <el-icon><Plus /></el-icon>
              添加步骤
            </el-button>
          </div>
        </el-form-item>
        
        <div class="steps-container">
          <div
            v-for="(step, index) in routeForm.steps"
            :key="step.tempId"
            class="step-item"
          >
            <div class="step-header">
              <span class="step-index">步骤 {{ index + 1 }}</span>
              <el-button
                type="danger"
                size="small"
                text
                @click="removeStep(index)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
            
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item :prop="`steps.${index}.stepName`" :rules="stepRules.stepName">
                  <el-input v-model="step.stepName" placeholder="步骤名称" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :prop="`steps.${index}.workCenter`" :rules="stepRules.workCenter">
                  <el-select v-model="step.workCenter" placeholder="工作中心" style="width: 100%">
                    <el-option label="装配线A" value="assembly_a" />
                    <el-option label="机加工B" value="machining_b" />
                    <el-option label="包装线C" value="packaging_c" />
                    <el-option label="测试台D" value="testing_d" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :prop="`steps.${index}.standardTime`" :rules="stepRules.standardTime">
                  <el-input-number
                    v-model="step.standardTime"
                    placeholder="标准工时"
                    :min="0"
                    :precision="2"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item>
                  <el-input v-model="step.equipment" placeholder="所需设备" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-input v-model="step.skillRequirement" placeholder="技能要求" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item>
              <el-input
                v-model="step.description"
                type="textarea"
                :rows="2"
                placeholder="步骤描述"
              />
            </el-form-item>
          </div>
        </div>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="routeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveRoute">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 工艺路线详情对话框 -->
    <el-dialog
      v-model="routeDetailVisible"
      title="工艺路线详情"
      width="800px"
    >
      <div v-if="selectedRoute" class="route-detail">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="路线编码">{{ selectedRoute.routeCode }}</el-descriptions-item>
          <el-descriptions-item label="路线名称">{{ selectedRoute.routeName }}</el-descriptions-item>
          <el-descriptions-item label="关联产品">{{ selectedRoute.productName }}</el-descriptions-item>
          <el-descriptions-item label="工艺类型">
            <el-tag :type="getProcessTypeColor(selectedRoute.processType)">{{ getProcessTypeText(selectedRoute.processType) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="版本号">{{ selectedRoute.version }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(selectedRoute.status)">{{ getStatusText(selectedRoute.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="总工时">{{ selectedRoute.totalTime }}小时</el-descriptions-item>
          <el-descriptions-item label="步骤数量">{{ selectedRoute.stepCount }}步</el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">{{ selectedRoute.description || '无' }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="steps-detail" style="margin-top: 20px;">
          <h3>工艺步骤</h3>
          <el-table :data="selectedRoute.steps" style="width: 100%">
            <el-table-column prop="stepName" label="步骤名称" />
            <el-table-column prop="workCenter" label="工作中心" />
            <el-table-column prop="standardTime" label="标准工时(h)" align="center" />
            <el-table-column prop="equipment" label="所需设备" />
            <el-table-column prop="skillRequirement" label="技能要求" />
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Upload,
  Download,
  Document,
  CircleCheck,
  Connection,
  TrendCharts,
  Search,
  Refresh,
  Grid,
  Share,
  ArrowDown,
  ArrowRight,
  Delete
} from '@element-plus/icons-vue'

// 响应式数据
const viewMode = ref('table')
const routeDialogVisible = ref(false)
const routeDetailVisible = ref(false)
const isEdit = ref(false)
const selectedRoute = ref(null)
const routeFormRef = ref(null)

// 统计数据
const routeStats = reactive({
  totalRoutes: 15,
  activeRoutes: 12,
  totalSteps: 68,
  avgEfficiency: 87
})

// 筛选表单
const filterForm = reactive({
  productName: '',
  processType: '',
  status: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 工艺路线表单
const routeForm = reactive({
  routeCode: '',
  routeName: '',
  productId: '',
  processType: '',
  version: '1.0',
  status: 'draft',
  description: '',
  steps: []
})

// 表单验证规则
const routeRules = {
  routeCode: [
    { required: true, message: '请输入路线编码', trigger: 'blur' }
  ],
  routeName: [
    { required: true, message: '请输入路线名称', trigger: 'blur' }
  ],
  productId: [
    { required: true, message: '请选择关联产品', trigger: 'change' }
  ],
  processType: [
    { required: true, message: '请选择工艺类型', trigger: 'change' }
  ]
}

const stepRules = {
  stepName: [
    { required: true, message: '请输入步骤名称', trigger: 'blur' }
  ],
  workCenter: [
    { required: true, message: '请选择工作中心', trigger: 'change' }
  ],
  standardTime: [
    { required: true, message: '请输入标准工时', trigger: 'blur' }
  ]
}

// 产品列表
const products = ref([
  { id: 1, name: '智能手机' },
  { id: 2, name: '平板电脑' },
  { id: 3, name: '笔记本电脑' },
  { id: 4, name: '智能手表' }
])

// 工艺路线数据
const routes = ref([
  {
    id: 1,
    routeCode: 'RT001',
    routeName: '智能手机装配工艺',
    productName: '智能手机',
    processType: 'assembly',
    stepCount: 8,
    totalTime: 12.5,
    status: 'active',
    version: '2.1',
    updateTime: '2025-01-15 14:30:00',
    isDefault: true,
    description: '智能手机标准装配工艺流程',
    steps: [
      {
        id: 1,
        stepName: '主板安装',
        workCenter: 'assembly_a',
        standardTime: 2.0,
        equipment: '精密螺丝刀',
        skillRequirement: '初级装配工',
        description: '将主板固定到机身'
      },
      {
        id: 2,
        stepName: '屏幕组装',
        workCenter: 'assembly_a',
        standardTime: 3.5,
        equipment: '压合机',
        skillRequirement: '中级装配工',
        description: '屏幕与机身组装'
      },
      {
        id: 3,
        stepName: '电池安装',
        workCenter: 'assembly_a',
        standardTime: 1.5,
        equipment: '绝缘工具',
        skillRequirement: '初级装配工',
        description: '安装电池模块'
      },
      {
        id: 4,
        stepName: '功能测试',
        workCenter: 'testing_d',
        standardTime: 2.0,
        equipment: '测试设备',
        skillRequirement: '测试工程师',
        description: '全功能测试验证'
      }
    ]
  },
  {
    id: 2,
    routeCode: 'RT002',
    routeName: '平板电脑加工工艺',
    productName: '平板电脑',
    processType: 'machining',
    stepCount: 6,
    totalTime: 8.0,
    status: 'active',
    version: '1.5',
    updateTime: '2025-01-14 10:20:00',
    isDefault: false,
    description: '平板电脑外壳加工工艺',
    steps: [
      {
        id: 5,
        stepName: '铝合金切割',
        workCenter: 'machining_b',
        standardTime: 2.5,
        equipment: 'CNC机床',
        skillRequirement: '数控操作工',
        description: '外壳材料切割'
      },
      {
        id: 6,
        stepName: '精密铣削',
        workCenter: 'machining_b',
        standardTime: 3.0,
        equipment: '精密铣床',
        skillRequirement: '高级机械工',
        description: '外壳精密加工'
      }
    ]
  },
  {
    id: 3,
    routeCode: 'RT003',
    routeName: '产品包装工艺',
    productName: '智能手机',
    processType: 'packaging',
    stepCount: 4,
    totalTime: 3.0,
    status: 'draft',
    version: '1.0',
    updateTime: '2025-01-13 16:45:00',
    isDefault: false,
    description: '产品标准包装流程',
    steps: [
      {
        id: 7,
        stepName: '产品检验',
        workCenter: 'packaging_c',
        standardTime: 0.5,
        equipment: '检验工具',
        skillRequirement: '质检员',
        description: '最终产品检验'
      },
      {
        id: 8,
        stepName: '包装装盒',
        workCenter: 'packaging_c',
        standardTime: 1.0,
        equipment: '包装机',
        skillRequirement: '包装工',
        description: '产品装入包装盒'
      }
    ]
  }
])

// 计算属性
const filteredRoutes = computed(() => {
  let result = routes.value
  
  if (filterForm.productName) {
    result = result.filter(route => 
      route.productName.toLowerCase().includes(filterForm.productName.toLowerCase()) ||
      route.routeName.toLowerCase().includes(filterForm.productName.toLowerCase())
    )
  }
  
  if (filterForm.processType) {
    result = result.filter(route => route.processType === filterForm.processType)
  }
  
  if (filterForm.status) {
    result = result.filter(route => route.status === filterForm.status)
  }
  
  pagination.total = result.length
  
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  
  return result.slice(start, end)
})

// 工具函数
const getProcessTypeText = (type) => {
  const typeMap = {
    assembly: '装配工艺',
    machining: '加工工艺',
    packaging: '包装工艺',
    testing: '测试工艺'
  }
  return typeMap[type] || type
}

const getProcessTypeColor = (type) => {
  const colorMap = {
    assembly: 'primary',
    machining: 'success',
    packaging: 'warning',
    testing: 'info'
  }
  return colorMap[type] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    active: '启用',
    inactive: '禁用',
    draft: '草稿'
  }
  return statusMap[status] || status
}

const getStatusType = (status) => {
  const typeMap = {
    active: 'success',
    inactive: 'danger',
    draft: 'warning'
  }
  return typeMap[status] || 'info'
}

// 事件处理函数
const setViewMode = (mode) => {
  viewMode.value = mode
}

const handleSearch = () => {
  pagination.currentPage = 1
}

const resetFilter = () => {
  Object.assign(filterForm, {
    productName: '',
    processType: '',
    status: ''
  })
  handleSearch()
}

const handleSelectionChange = (selection) => {
  console.log('选中的工艺路线:', selection)
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
}

const selectRoute = (route) => {
  selectedRoute.value = route
}

const showCreateDialog = () => {
  isEdit.value = false
  resetRouteForm()
  routeDialogVisible.value = true
}

const viewRoute = (route) => {
  selectedRoute.value = route
  routeDetailVisible.value = true
}

const editRoute = (route) => {
  isEdit.value = true
  selectedRoute.value = route
  
  // 填充表单数据
  Object.assign(routeForm, {
    routeCode: route.routeCode,
    routeName: route.routeName,
    productId: products.value.find(p => p.name === route.productName)?.id || '',
    processType: route.processType,
    version: route.version,
    status: route.status,
    description: route.description,
    steps: route.steps.map(step => ({ ...step, tempId: Date.now() + Math.random() }))
  })
  
  routeDialogVisible.value = true
}

const handleCommand = ({ action, row }) => {
  switch (action) {
    case 'copy':
      copyRoute(row)
      break
    case 'version':
      manageVersion(row)
      break
    case 'activate':
      toggleRouteStatus(row, 'active')
      break
    case 'deactivate':
      toggleRouteStatus(row, 'inactive')
      break
    case 'delete':
      deleteRoute(row)
      break
  }
}

const copyRoute = (route) => {
  ElMessage.success(`复制工艺路线: ${route.routeName}`)
}

const manageVersion = (route) => {
  ElMessage.info(`版本管理功能开发中: ${route.routeName}`)
}

const toggleRouteStatus = (route, status) => {
  route.status = status
  ElMessage.success(`工艺路线状态已更新: ${getStatusText(status)}`)
}

const deleteRoute = (route) => {
  ElMessageBox.confirm(
    `确定要删除工艺路线 "${route.routeName}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = routes.value.findIndex(r => r.id === route.id)
    if (index > -1) {
      routes.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const addStep = () => {
  routeForm.steps.push({
    tempId: Date.now() + Math.random(),
    stepName: '',
    workCenter: '',
    standardTime: 0,
    equipment: '',
    skillRequirement: '',
    description: ''
  })
}

const removeStep = (index) => {
  routeForm.steps.splice(index, 1)
}

const resetRouteForm = () => {
  Object.assign(routeForm, {
    routeCode: '',
    routeName: '',
    productId: '',
    processType: '',
    version: '1.0',
    status: 'draft',
    description: '',
    steps: []
  })
  
  if (routeFormRef.value) {
    routeFormRef.value.resetFields()
  }
}

const saveRoute = () => {
  routeFormRef.value.validate((valid) => {
    if (valid) {
      if (isEdit.value) {
        // 更新现有路线
        const index = routes.value.findIndex(r => r.id === selectedRoute.value.id)
        if (index > -1) {
          const product = products.value.find(p => p.id === routeForm.productId)
          routes.value[index] = {
            ...routes.value[index],
            routeCode: routeForm.routeCode,
            routeName: routeForm.routeName,
            productName: product?.name || '',
            processType: routeForm.processType,
            version: routeForm.version,
            status: routeForm.status,
            description: routeForm.description,
            steps: routeForm.steps,
            stepCount: routeForm.steps.length,
            totalTime: routeForm.steps.reduce((sum, step) => sum + (step.standardTime || 0), 0),
            updateTime: new Date().toLocaleString()
          }
        }
        ElMessage.success('工艺路线更新成功')
      } else {
        // 创建新路线
        const product = products.value.find(p => p.id === routeForm.productId)
        const newRoute = {
          id: Date.now(),
          routeCode: routeForm.routeCode,
          routeName: routeForm.routeName,
          productName: product?.name || '',
          processType: routeForm.processType,
          version: routeForm.version,
          status: routeForm.status,
          description: routeForm.description,
          steps: routeForm.steps,
          stepCount: routeForm.steps.length,
          totalTime: routeForm.steps.reduce((sum, step) => sum + (step.standardTime || 0), 0),
          updateTime: new Date().toLocaleString(),
          isDefault: false
        }
        routes.value.unshift(newRoute)
        ElMessage.success('工艺路线创建成功')
      }
      
      routeDialogVisible.value = false
      resetRouteForm()
    }
  })
}

const importRoutes = () => {
  ElMessage.success('导入功能开发中')
}

const exportRoutes = () => {
  ElMessage.success('导出功能开发中')
}

// 生命周期
onMounted(() => {
  // 初始化数据
})
</script>

<style scoped>
.process-route-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.header-left h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.header-left p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 12px;
}

.stats-overview {
  margin-bottom: 20px;
}

.stats-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stats-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stats-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stats-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stats-icon.active {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stats-icon.steps {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stats-icon.efficiency {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
}

.stats-label {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

.filter-card,
.table-card {
  margin-bottom: 20px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.route-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.route-name .name {
  font-weight: 500;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 流程视图样式 */
.flow-view {
  padding: 20px 0;
}

.flow-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.flow-route {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 20px;
  background: white;
  cursor: pointer;
  transition: all 0.2s;
}

.flow-route:hover,
.flow-route.route-selected {
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.route-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;
}

.route-header h3 {
  margin: 0;
  color: #303133;
}

.route-flow {
  display: flex;
  align-items: center;
  gap: 16px;
  overflow-x: auto;
  padding: 10px 0;
}

.flow-step {
  display: flex;
  align-items: center;
  gap: 16px;
}

.step-node {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #ebeef5;
  min-width: 200px;
}

.step-number {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 600;
  flex-shrink: 0;
}

.step-content {
  flex: 1;
}

.step-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.step-info {
  font-size: 12px;
  color: #909399;
  display: flex;
  gap: 8px;
}

.step-arrow {
  color: #909399;
  font-size: 16px;
}

/* 表单样式 */
.form-section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #303133;
}

.steps-container {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 16px;
  background: #fafafa;
}

.step-item {
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
}

.step-item:last-child {
  margin-bottom: 0;
}

.step-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.step-index {
  font-weight: 600;
  color: #409eff;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.route-detail {
  padding: 20px 0;
}

.steps-detail h3 {
  margin: 0 0 16px 0;
  color: #303133;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .process-route-management {
    padding: 12px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .header-right {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  
  .route-flow {
    flex-direction: column;
    align-items: stretch;
  }
  
  .flow-step {
    flex-direction: column;
  }
  
  .step-arrow {
    transform: rotate(90deg);
  }
  
  .step-node {
    min-width: auto;
  }
}
</style>